<template>
  <NuxtLayout name="userCenter">
    <div class="bg-gray-800 rounded-lg p-6">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-white">观看历史</h2>
        <el-button
          v-if="historyList && historyList.length > 0"
          @click="handleClearHistory"
          type="danger"
          size="small"
        >
          清空历史
        </el-button>
      </div>

      <!-- 加载中 -->
      <div v-if="loading" class="text-center py-12">
        <el-icon class="is-loading" :size="32" color="#409EFF">
          <Loading />
        </el-icon>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!historyList || historyList.length === 0" class="text-center py-12">
        <el-empty description="暂无观看记录">
          <el-button type="primary" @click="navigateTo('/')">去观看影片</el-button>
        </el-empty>
      </div>

      <!-- 历史列表 -->
      <div v-else class="space-y-4">
        <el-card
          v-for="item in historyList"
          :key="item.historyId"
          class="history-card"
          :body-style="{ padding: '16px' }"
        >
          <div class="flex gap-4">
            <!-- 海报 -->
            <NuxtLink :to="`/movie/${item.movieId}`" class="flex-shrink-0">
              <el-image
                :src="item.moviePoster || '/placeholder.jpg'"
                :alt="item.movieTitle"
                class="w-32 h-20 object-cover rounded"
                fit="cover"
              >
                <template #error>
                  <div class="w-32 h-20 flex items-center justify-center bg-gray-700 rounded">
                    <el-icon :size="24" color="#999">
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </NuxtLink>

            <!-- 信息 -->
            <div class="flex-1">
              <div class="flex justify-between items-start">
                <div class="flex-1">
                  <NuxtLink
                    :to="`/movie/${item.movieId}`"
                    class="text-lg font-medium text-white hover:text-blue-400 transition-colors"
                  >
                    {{ item.movieTitle }}
                    <span v-if="item.episodeName" class="text-sm text-gray-400">
                      - {{ item.episodeName }}
                    </span>
                  </NuxtLink>

                  <div class="mt-2 flex items-center gap-4 text-sm text-gray-400">
                    <span>观看至 {{ formatProgress(item.watchProgress) }}%</span>
                    <span v-if="item.watchDuration">
                      {{ formatDuration(item.watchDuration) }} / {{ formatDuration(item.totalDuration) }}
                    </span>
                    <span>{{ formatRelativeTime(item.watchTime) }}</span>
                  </div>
                </div>

                <div class="flex items-center gap-2 ml-4">
                  <el-button
                    size="small"
                    type="primary"
                    @click="continueWatching(item)"
                  >
                    继续观看
                  </el-button>

                  <el-button
                    size="small"
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="handleRemoveHistory(item)"
                  />
                </div>
              </div>

              <!-- 进度条 -->
              <el-progress
                :percentage="item.watchProgress || 0"
                :stroke-width="6"
                color="#409EFF"
                class="mt-3"
              />
            </div>
          </div>
        </el-card>

        <!-- 分页 -->
        <div v-if="total > pageSize" class="mt-6 flex justify-center">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Loading, Picture } from '@element-plus/icons-vue'

definePageMeta({
  middleware: 'auth'
})

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const historyList = ref<any[]>([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取观看历史
const getHistoryList = async () => {
  loading.value = true
  try {
    const data = await $fetch('/dev-api/member/history/list', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })

    if (data.code === 200) {
      historyList.value = data.rows || []
      total.value = data.total || 0
    }
  } catch (error: any) {
    console.error('获取观看历史失败:', error)
    ElMessage.error(error.data?.msg || '获取观看历史失败')
  } finally {
    loading.value = false
  }
}

// 格式化进度
const formatProgress = (progress: number) => {
  return Math.round(progress || 0)
}

// 格式化时长
const formatDuration = (seconds: number) => {
  if (!seconds) return '00:00'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 格式化相对时间
const formatRelativeTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60))
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60))
      return minutes === 0 ? '刚刚' : `${minutes}分钟前`
    }
    return `${hours}小时前`
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 继续观看
const continueWatching = (item: any) => {
  // 跳转到播放页面，传递进度参数
  router.push(`/movie/play/${item.movieId}?progress=${item.watchDuration || 0}`)
}

// 删除单个历史
const handleRemoveHistory = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除《${item.movieTitle}》的观看记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const data = await $fetch(`/dev-api/member/history/${item.historyId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (data.code === 200) {
      ElMessage.success('删除成功')
      await getHistoryList()
    } else {
      ElMessage.error(data.msg || '删除失败')
    }
  } catch (error) {
    // 用户取消操作，不做处理
    if (error !== 'cancel') {
      console.error('删除历史失败:', error)
    }
  }
}

// 清空所有历史
const handleClearHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有观看历史吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const data = await $fetch('/dev-api/member/history/clear', {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (data.code === 200) {
      ElMessage.success('清空成功')
      historyList.value = []
      total.value = 0
    } else {
      ElMessage.error(data.msg || '清空失败')
    }
  } catch (error) {
    // 用户取消操作，不做处理
    if (error !== 'cancel') {
      console.error('清空历史失败:', error)
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getHistoryList()
}

const handlePageChange = (val: number) => {
  pageNum.value = val
  getHistoryList()
}

onMounted(() => {
  getHistoryList()
})

// SEO设置
useSeoMeta({
  title: '观看历史',
  description: '查看您的观看历史记录',
})
</script>

<style scoped>
.history-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__body) {
  padding: 16px !important;
}

:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-button-disabled-color: rgba(255, 255, 255, 0.3);
  --el-pagination-hover-color: #409EFF;
}

:deep(.el-progress__text) {
  color: rgba(255, 255, 255, 0.8) !important;
  font-size: 12px !important;
}
</style>